package com.stationbuilding.fragment.document;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.stationbuilding.R;
import com.stationbuilding.TestData;
import com.stationbuilding.adapter.ShowPhotoAdapter;
import com.stationbuilding.adapter.document.DocumentListAdapter;
import com.stationbuilding.adapter.home.HomeListAdapter;
import com.stationbuilding.bean.DocumentBean;
import com.stationbuilding.bean.FileBean;
import com.stationbuilding.bean.MemberBean;
import com.stationbuilding.bean.QuestionBean;
import com.stationbuilding.utils.PinyinComparator;
import com.stationbuilding.utils.PinyinUtil;
import com.stationbuilding.utils.PreferenceHelper;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DocumentFragment extends Fragment {

    private View view;
    private LinearLayout search;
    private EditText searchEdit;
    private Dialog dialog;
    private DocumentListAdapter documentListAdapter;
    private List<DocumentBean> documentList = new ArrayList<>();
    private int selectedPosition = -1;
    private String token = PreferenceHelper.getInstance(getActivity()).getToken();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_doucument, container, false);
        search = (LinearLayout) view.findViewById(R.id.search);
        searchEdit = (EditText) view.findViewById(R.id.search_edit);
        initEvent();
        initListView();
        return view;
    }

    /**
     * 初始化搜索图片按钮
     */
    private void initEvent() {
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search.setVisibility(View.GONE);
                searchEdit.setVisibility(View.VISIBLE);
                searchEdit.requestFocus();
                InputMethodManager inputMethodManager = (InputMethodManager)searchEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
            }
        };
        search.setOnClickListener(onClickListener);
        // 根据输入框输入值的改变来过滤搜索
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        search.setOnClickListener(onClickListener);
    }

    /**
     * 初始化待办任务列表
     */
    private void initListView() {
        ListView documentListView = (ListView) view.findViewById(R.id.document_list);
        documentListAdapter = new DocumentListAdapter(documentList);
        documentListView.setAdapter(documentListAdapter);
        documentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                documentListAdapter.setSelectedPosition(position);
                documentListAdapter.notifyDataSetChanged();
                selectedPosition = position;
            }
        });
        loadData();
    }

    /**
     * 数据加载
     */
    private void loadData() {
        filledData(TestData.getDocumentData());
        documentListAdapter.setList(documentList);
        documentListAdapter.notifyDataSetChanged();
//        RetrofitManager.toSubscribe(
//                RetrofitManager.getApiService().getQuestionListByStatus(token, expandId, Constants.QUESTION_TYPE_QUALITY, initiator),
//                new Observer<QuestionListBean>() {
//
//                    @Override
//                    public void onComplete() {
//                        DialogUtils.closeDialog(dialog);
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
//                        DialogUtils.closeDialog(dialog);
//                    }
//
//                    @Override
//                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
//                        dialog = DialogUtils.createLoadingDialog(getActivity(), "数据加载中...");
//                    }
//
//                    @Override
//                    public void onNext(QuestionListBean questionListBean) {
//                        questionList = questionListBean.getQuestionList();
//                        homeListAdapter.setList(questionList);
//                        homeListAdapter.notifyDataSetChanged();
//                    }
//                });
    }

    private void filledData(List<DocumentBean> documentBeanList) {
        ArrayList<String> indexString = new ArrayList<>();

        for (DocumentBean documentBean : documentBeanList) {
            String pinyin = PinyinUtil.getPingYin(documentBean.getDocumentName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                documentBean.setSortLetters(sortString.toUpperCase());
            }
            documentList.add(documentBean);
        }
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    public void filterData(String filterStr) {
        List<DocumentBean> sortList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr)) {
            sortList = documentList;
        } else {
            sortList.clear();
            for (DocumentBean documentBean : documentList) {
                String documentName = documentBean.getDocumentName();
                if (documentName.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1 || PinyinUtil.getPingYin(documentName).toUpperCase().startsWith(filterStr.toString().toUpperCase())) {
                    sortList.add(documentBean);
                }
            }
        }
        documentListAdapter.updateListView(sortList);
    }

    /**
     * 设置选择结果
     */
    public void setResult() {
        if (selectedPosition == -1) {
            Toast.makeText(getActivity(), "请选择关联资料！", Toast.LENGTH_SHORT).show();
            return;
        }
        DocumentBean documentBean = documentList.get(selectedPosition);
        if (documentBean.getDocumentType() == 0) {
            Toast.makeText(getActivity(), "不能选择文件夹，请选择文件！", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("id", documentBean.getDocumentId());
        intent.putExtra("name", documentBean.getDocumentName());
        getActivity().setResult(Activity.RESULT_OK, intent);
        getActivity().finish();
    }
}
